#! /usr/bin/env python
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2021 wanghch <wanghch@wanghch-pc>
#
# Distributed under terms of the MIT license.

"""

"""
# jqdatasdk for local use
from jqdatasdk import *
from jq_utils import *

# jqdata for offical website use
# from jqdata import *
import datetime
import numpy as np
import pandas as pd
import os
pd.reset_option('display.float_format')

sdk_auth()
industry_id_file = "./industry_id.csv"

#industry = get_industries(name='zjw', date=None)
#print(industry)
# {'600519.XSHG': {'sw_l1': {'industry_code': '801120', 'industry_name': '食品饮料I'}, 'sw_l2': {'industry_code': '801123', 'industry_name': '饮料制造II'}, 'sw_l3': {'industry_code': '851231', 'industry_name': '白酒III'}, 'zjw': {'industry_code': 'C15', 'industry_name': '酒、饮料和精制茶制造业'}, 'jq_l2': {'industry_code': 'HY478', 'industry_name': '白酒与葡萄酒指数'}, 'jq_l1': {'industry_code': 'HY005', 'industry_name': '日常消费指数'}}}
def get_code_sw(industry_map):
    df = pd.read_csv("clist.csv")
    header = ["code", "name", "swl1_id", "swl2_id", "swl3_id",  "swl1", "swl2", "swl3", "swn1", "swn2", "swn3"]
    with open("industry.csv", "w") as fw:
        fw.write(",".join(header) + "\n")
        for index, row in df.iterrows():
            code = row['code']
            d = get_industry(code)
            swl1 = d[code]["sw_l1"]["industry_code"]
            swl2 = d[code]["sw_l2"]["industry_code"]
            swl3 = d[code]["sw_l3"]["industry_code"]

            swn1 = d[code]["sw_l1"]["industry_name"]
            swn2 = d[code]["sw_l2"]["industry_name"]
            swn3 = d[code]["sw_l3"]["industry_name"]


            swl1_id = industry_map[swl1]
            swl2_id = industry_map[swl2]
            swl3_id = industry_map[swl3]


            info = [code, row['display_name'], str(swl1_id), str(swl2_id), str(swl3_id),  swl1, swl2, swl3, swn1, swn2, swn3]

            fw.write(",".join(info) + "\n")

def get_industry_sw():
    if os.path.exists(industry_id_file):
        lm = {}
        with open(industry_id_file, "r") as iif:
            for line in iif:
                ltype, lid, idx = line.strip().split(",")
                lm[lid] = int(idx)
        return lm
    l1 = sorted(get_industries(name='sw_l1').index.values)
    l2 = sorted(get_industries(name='sw_l2').index.values)
    l3 = sorted(get_industries(name='sw_l3').index.values)

    lm = {}
    lm1 = dict(zip(l1, range(len(l1))))
    lm2 = dict(zip(l2, range(len(l2))))
    lm3 = dict(zip(l3, range(len(l3))))
    with open("industry_id.csv", "w") as fw:
        for lid, idx in lm1.items():
            fw.write("sw1,"+ lid  + "," + str(idx) + "\n")
        for lid, idx in lm2.items():
            fw.write("sw2," + lid  + "," + str(idx) + "\n")
        for lid, idx in lm3.items():
            fw.write("sw3," + lid  + "," + str(idx) + "\n")
    return lm



ind_id = get_industry_sw()
#print(ind_id)

get_code_sw(ind_id)
